$(function(){
	var travelerGeneral = $('#traveler-general');
	var travelerShortGeneral = $('#traveler-short-general');

	var travelersNumberChange = function() {
		var travelers = $('#added-travellers .added-traveller-short').size();
		$('#number_travelers_hidden').val(travelers);
	};

	$('#btn-traveler-add').click(function() {
		var $this = $(this);
		var selectTravelers = $('#select-travelers').val();
		if (selectTravelers == '') {
			$this.attr('disabled', 'disabled');
			$('#select-travelers').attr('disabled', 'disabled');
			var traveler = travelerGeneral.clone(true).removeAttr('id');
			$this.parents('.row').after(traveler);
			traveler.show();
			$('.btn-traveler-cancel').one('click', function() {
				$(this).parents('div.traveler').remove();
				$this.removeAttr('disabled');
				$('#select-travelers').removeAttr('disabled');
			});
			$('.btn-traveler-ok').bind('click', addTravelerFn);
		} else {
			var travelerIndex = '<input type="hidden" name="traveler_indexes[]" value="'+ selectTravelers +'" />';
			var existingTraveller = travelerShortGeneral.clone(true).removeAttr('id');
			existingTraveller.find('.traveler-edit').remove();
			existingTraveller.find('.row .body').prepend($('#select-travelers option:selected').text());
			existingTraveller.append(travelerIndex);
			$('#added-travellers').prepend(existingTraveller);
		}
		travelersNumberChange();
	});

	var travelerEditClick = function() {
		var next = $(this).parents('.added-traveller-short').next('.added-traveller');
		if (next.is(':hidden')) {
			next.show();
		} else {
			next.hide();
		}
	};

	var travelerRemoveClick = function() {
		if (confirm('REMOVE_TRAVELER_QUESTION'.translate())) {
			$(this).parents('.added-traveller-short').next('.added-traveller').remove();
			$(this).parents('.added-traveller-short').remove();
			travelersNumberChange();
		}
	};

	$('.traveler-edit').bind('click', travelerEditClick);
	$('.traveler-remove').bind('click', travelerRemoveClick);

	var btnTravelerEditFn = function() {
		var addedTraveler = $(this).parents('div.added-traveller');
		var firstName = addedTraveler.find('input.traveler_name_first').val();
		var lastName = addedTraveler.find('input.traveler_name_last').val();
		addedTraveler.prev('div.added-traveller-short').find('span.full-name').text(firstName + ' ' + lastName);
	};

	var namesKeyupBind = function() {
		$('div.added-traveller input.traveler_name_first, div.added-traveller input.traveler_name_last').keyup(btnTravelerEditFn);
	};

	namesKeyupBind();

	var addTravelerFn = function() {
		$('#btn-traveler-add').removeAttr('disabled');
		$('#select-travelers').removeAttr('disabled');
		var
			block = $(this).parents('div.traveler'),
			blockDesc = block.find('div.traveler-desc'),
			continue_ = true,
			travelerShort = travelerShortGeneral.clone(true).removeAttr('id')
		;

		var arr = [];
		block.find('select').each(function() {
			arr.push($(this).val());
		});

		blockDesc.find('input').each(function() {
			if ($.trim($(this).val()) == '') {
				continue_ = false;
			}
		});

		blockDesc.find('select').each(function() {
			if ($.trim($(this).val()) == '') {
				continue_ = false;
			}
		});

		if (continue_) {
			$(this).parents('div.row').remove();
			var blockNew = block.clone(true);
			blockNew.find('select').each(function(i) {
				$(this).val(arr[i]);
			});
			travelerShort.find('.row .body .full-name').append(blockNew.find('input.traveler_name_first').val() + ' ' + blockNew.find('input.traveler_name_last').val());
			$('#added-travellers').prepend(blockNew);
			$('#added-travellers').prepend(travelerShort);
			blockNew.removeClass('traveler').addClass('added-traveller');
			namesKeyupBind();
			block.remove();
		} else {
			alert('FILL_FIELDS'.translate());
		}
		travelersNumberChange();
	};

	travelerGeneral.parents('form').submit(function() {
		$('#traveler-general').remove();
		var dd = $('input.start-date').val().substr(0,2);
		var mm = $('input.start-date').val().substr(3,2);
		var yyyy = $('input.start-date').val().substr(6,4);
		var startDate = new Date(mm + '/' + dd + '/' + yyyy);
		var dd1 = $('input.end-date').val().substr(0,2);
		var mm1 = $('input.end-date').val().substr(3,2);
		var yyyy1 = $('input.end-date').val().substr(6,4);
		var endDate = new Date(mm1 + '/' + dd1 + '/' + yyyy1);
		if (endDate < startDate) {
			alert('STARTDATE_MUST_BE_LESS_ENDDATE'.translate());
			return false;
		}
		var continue_ = true;
		var notfilled = false;
		$('.added-traveler-desc input, .added-traveler-desc select').each(function() {
			if ($.trim($(this).val()) == '') {
				continue_ = false;
				notfilled = true;
			}
		});
		if (notfilled) {
			$('.added-traveller').show();
			alert('TRAVELER_EDIT_REQUIRED_NOT_FILLED'.translate());
		}
		$('.cancel-conditions input').each(function() {
			if ($(this).val() != '' && $(this).val() != $(this).val().match(/[0-9]+/gi) && continue_) {
				alert('DAYS_SUM_NUST_BE_NUMBERS'.translate());
				continue_ = false;
			}
		});
		if (!continue_) {
			return false;
		}
});

	var productTypeFormAction = $('#form-product-type').attr('action');
	$('#select-product-type').change(function() {
		$(this).parents('form').attr('action', productTypeFormAction + $(this).val()).submit();
	});

	/* validation */
	var
		mesReq = 'REQUIRED_FIELD'.translate(),
		mesNumber = 'INPUT_CORRECT_NUMBER'.translate(),
		mes_min = 'INPUT_VALUE_MORE_0'.translate()
	;

	$.validator.messages.required = mesReq;
	$.validator.messages.number = mesNumber;

	$('#frm-product-edit').validate({
		errorClass: 'invalid',
		messages: {
			product_net_price_currency_value: {
				required: 'NET_CURRENCY_REQUIRED'.translate()
			},
			product_net_price_value: {
				required: 'VALUE_NET_REQUIRED'.translate(),
				min: mes_min
			},
			product_deposit_price_value: {
				min: mes_min
			},
			product_on_arrival_price_value: {
				min: mes_min
			}
		},
		rules: {
			product_net_price_value: {
				number: true,
				min: 0
			},
			product_deposit_price_value: {
				number: true,
				min: 0
			},
			product_on_arrival_price_value: {
				number: true,
				min: 0
			}
		},
		errorPlacement: function(error, element) {
			if (element.hasClass('date-picker'))
				error.insertAfter(element.parents('.datepicker_wrap'));
			else if (element.attr('name') == 'product_net_price_currency_value')
				error.appendTo(element.parents('div.body'));
			else
				error.insertAfter(element);
		}
	});

	$('#country-name').change(function() {
		var s = $(this);
		var t = $('#selector-city'), p = {id: s.val()};
        t.html('<option value="">Загрузка...</option>');
        t.attr('disabled', 'disabled');
        $.get('/a_ajax/location.getOptionsCity', p, function (data) {
            t.attr('disabled', '');
            var h = '';
            h += '<option value="" selected="selected" class="first">' + s.attr('deftext') + '</option>';
            t.html(h + data);
        });
	});

	var productNetDepositPriceCurrency = $('#product-net-deposit-price-currency');
	var productNetOnArrivalPriceCurrency = $('#product-net-on-arrival-price-currency');

	productNetDepositPriceCurrency.change(function() {
		productNetOnArrivalPriceCurrency.val($(this).val());
	});

	productNetOnArrivalPriceCurrency.change(function() {
		productNetDepositPriceCurrency.val($(this).val());
	});

	$('#calculate-price').click(function() {
		$.ajax({
			async   : false,
			type    : "GET",
			url     : "/a_admin/order.calculatePrices",
			dataType: "json",
			data    : {
				order_item_id: $('#order-item-id').val(),
				product_net_deposit_price_currency: productNetDepositPriceCurrency.val(),
				product_net_deposit_price:  $('#product-net-deposit-price').val(),
				product_net_on_arrival_price_currency: productNetOnArrivalPriceCurrency.val(),
				product_net_on_arrival_price: $('#product-net-on-arrival-price').val()
			},
			success : function(data) {
				if (data.error == 0) {
					$('#product-deposit-price').val(data.depositPrice);
					$('#product-on-arrival-price').val(data.onArrivalPrice);
				}
			}
		});
	});
});